package com.ruoyi.common.utils;


import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class Base64Util {
   /* private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

    private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60,
            61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1,
            -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };

    private Base64Util() {
    }

    *//**
     * 将字节数组编码为字符串
     *
     * @param data
     *//*
    public static String encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;

        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    public static byte[] decode(String str) throws Exception {
        byte[] data = str.getBytes("GBK");
        int len = data.length;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
        int i = 0;
        int b1, b2, b3, b4;

        while (i < len) {

            *//* b1 *//*
            do {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1) {
                break;
            }

            *//* b2 *//*
            do {
                b2 = base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1) {
                break;
            }
            buf.write((b1 << 2) | ((b2 & 0x30) >>> 4));

            *//* b3 *//*
            do {
                b3 = data[i++];
                if (b3 == 61) {
                    return buf.toByteArray();
                }
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) {
                break;
            }
            buf.write(((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2));

            *//* b4 *//*
            do {
                b4 = data[i++];
                if (b4 == 61) {
                    return buf.toByteArray();
                }
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) {
                break;
            }
            buf.write(((b3 & 0x03) << 6) | b4);
        }
        return buf.toByteArray();
    }


    public static void main(String[] args) {
        System.out.println(encryptNumber("17"));
        System.out.println(decryptNumber("cSHYg9="));
    }

    public static String encryptNumber(String number) {
        // 验证输入是否为纯数字
        if (!number.matches("\\d+")) {
            throw new IllegalArgumentException("Input must be numeric");
        }

        // 数字到字符的映射表
        Map<Character, Character> mapping = new HashMap<>();
        mapping.put('0', 'k');
        mapping.put('1', 'p');
        mapping.put('2', 'm');
        mapping.put('3', 'n');
        mapping.put('4', 'b');
        mapping.put('5', 'v');
        mapping.put('6', 'c');
        mapping.put('7', 'x');
        mapping.put('8', 'z');
        mapping.put('9', 'l');

        // 将数字转换为映射字符
        StringBuilder mapped = new StringBuilder();
        for (char c : number.toCharArray()) {
            mapped.append(mapping.get(c));
        }

        // Base64编码
        String base64 = Base64.getEncoder().encodeToString(mapped.toString().getBytes());

        // 添加随机字符干扰（在每个字符之间插入随机字符）
        StringBuilder result = new StringBuilder();
        String randomChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();

        for (char c : base64.toCharArray()) {
            result.append(c);
            // 在每个字符后添加一个随机字符（最后一个字符除外）
            if (result.length() < base64.length() * 2 - 1) {
                char randomChar = randomChars.charAt(random.nextInt(randomChars.length()));
                result.append(randomChar);
            }
        }

        return result.toString();
    }


    // 解密函数
    public static String decryptNumber(String encrypted) {
        // 移除随机字符干扰
        StringBuilder base64 = new StringBuilder();
        for(int i = 0; i < encrypted.length(); i += 2) {
            base64.append(encrypted.charAt(i));
        }

        // Base64解码
        byte[] decoded = Base64.getDecoder().decode(base64.toString());
        String mapped = new String(decoded);

        // 反向映射表
        Map<Character, Character> reverseMapping = new HashMap<>();
        reverseMapping.put('k', '0');
        reverseMapping.put('p', '1');
        reverseMapping.put('m', '2');
        reverseMapping.put('n', '3');
        reverseMapping.put('b', '4');
        reverseMapping.put('v', '5');
        reverseMapping.put('c', '6');
        reverseMapping.put('x', '7');
        reverseMapping.put('z', '8');
        reverseMapping.put('l', '9');

        // 将字符转回数字
        StringBuilder result = new StringBuilder();
        for(char c : mapped.toCharArray()) {
            result.append(reverseMapping.get(c));
        }

        return result.toString();
    }

   *//* public static boolean isBase64Encrypted(String str) {
        // 空值检查
        if (str == null || str.trim().isEmpty()) {
            return false;
        }

        try {
            // 检查长度是否为4的倍数
            if (str.length() % 4 != 0) {
                return false;
            }

            // 检查是否只包含合法Base64字符
            String base64Pattern = "^[A-Za-z0-9+/]*={0,2}$";
            if (!str.matches(base64Pattern)) {
                return false;
            }

            // 尝试解码,如果能成功解码说明是有效的Base64
            Base64.getDecoder().decode(str);
            return true;

        } catch (IllegalArgumentException e) {
            // 解码失败,说明不是有效的Base64格式
            return false;
        }
    }*//*

    public static boolean isBase64Encrypted(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }

        try {
            // 1. 先移除间隔的随机字符(偶数位的字符)
            StringBuilder cleanStr = new StringBuilder();
            for (int i = 0; i < str.length(); i++) {
                if (i % 2 == 0) {  // 只保留原始Base64的字符
                    cleanStr.append(str.charAt(i));
                }
            }

            // 2. 验证清理后的字符串是否为有效的Base64
            String base64Str = cleanStr.toString();
            // Base64.getDecoder().decode(base64Str);

            // 3. 解码后检查字符是否都在映射表中
            String decoded = new String(Base64.getDecoder().decode(base64Str));
            String validChars = "kpmnbvcxzl";  // 映射表中的所有值
            for (char c : decoded.toCharArray()) {
                if (validChars.indexOf(c) == -1) {
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }*/

    private static final char[] base64EncodeChars = new char[]{
                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Q', 'Z'
            };

    private static final byte[] base64DecodeChars = new byte[256];

    static {
        try {
            // 初始化解码表
            for (int i = 0; i < 256; i++) {
                base64DecodeChars[i] = -1;
            }
            for (int i = 0; i < 64; i++) {
                base64DecodeChars[base64EncodeChars[i]] = (byte) i;
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize Base64Util: " + e.getMessage());
        }
    }

    // 私有构造函数，防止实例化
    private Base64Util() {
    }

    /**
     * 编码byte数组到Base64字符串
     */
    public static String encode(byte[] data) {
        if (data == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;

        try {
            while (i < len) {
                b1 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                    sb.append("==");
                    break;
                }
                b2 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                    sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                    sb.append("=");
                    break;
                }
                b3 = data[i++] & 0xff;
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
                sb.append(base64EncodeChars[b3 & 0x3f]);
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 解码Base64字符串到byte数组
     */
    public static byte[] decode(String str) {
        if (str == null) {
            return null;
        }

        try {
            byte[] data = str.getBytes("UTF-8");
            int len = data.length;
            ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
            int i = 0;
            int b1 = 0, b2 = 0, b3, b4;

            while (i < len) {
                /* b1 */
                do {
                    if (i >= len) {
                        break;
                    }
                    b1 = base64DecodeChars[data[i++] & 0xff];
                } while (i < len && b1 == -1);
                if (b1 == -1) {
                    break;
                }

                /* b2 */
                do {
                    if (i >= len) {
                        break;
                    }
                    b2 = base64DecodeChars[data[i++] & 0xff];
                } while (i < len && b2 == -1);
                if (b2 == -1) {
                    break;
                }
                buf.write((b1 << 2) | ((b2 & 0x30) >>> 4));

                /* b3 */
                do {
                    if (i >= len) {
                        return buf.toByteArray();
                    }
                    b3 = data[i++] & 0xff;
                    if (b3 == '=') {
                        return buf.toByteArray();
                    }
                    b3 = base64DecodeChars[b3];
                } while (i < len && b3 == -1);
                if (b3 == -1) {
                    break;
                }
                buf.write(((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2));

                /* b4 */
                do {
                    if (i >= len) {
                        return buf.toByteArray();
                    }
                    b4 = data[i++] & 0xff;
                    if (b4 == '=') {
                        return buf.toByteArray();
                    }
                    b4 = base64DecodeChars[b4];
                } while (i < len && b4 == -1);
                if (b4 == -1) {
                    break;
                }
                buf.write(((b3 & 0x03) << 6) | b4);
            }
            return buf.toByteArray();
        } catch (Exception e) {
            return new byte[0];
        }
    }

    /**
     * 加密数字字符串，确保结果只包含字母和数字，没有特殊字符
     */
    public static String encryptNumber(String number) {
        try {
            // 验证输入是否为纯数字
            if (number == null || !number.matches("\\d+")) {
                throw new IllegalArgumentException("Input must be numeric");
            }

            // 数字到字符的映射表
            Map<Character, Character> mapping = new HashMap<>();
            mapping.put('0', 'k');
            mapping.put('1', 'p');
            mapping.put('2', 'm');
            mapping.put('3', 'n');
            mapping.put('4', 'b');
            mapping.put('5', 'v');
            mapping.put('6', 'c');
            mapping.put('7', 'x');
            mapping.put('8', 'z');
            mapping.put('9', 'l');

            // 将数字转换为映射字符
            StringBuilder mapped = new StringBuilder();
            for (char c : number.toCharArray()) {
                mapped.append(mapping.get(c));
            }

            // Base64编码
            String encoded = encode(mapped.toString().getBytes("UTF-8"));

            // 去除等号填充符
            encoded = encoded.replaceAll("=", "");

            // 不需要替换特殊字符，因为我们的字符表只包含字母和数字

            // 确保长度至少为4
            if (encoded.length() < 4) {
                StringBuilder sb = new StringBuilder(encoded);
                while (sb.length() < 4) {
                    sb.append('A');
                }
                encoded = sb.toString();
            }

            return encoded;
        } catch (Exception e) {
            return number; // 失败时返回原始输入
        }
    }

    /**
     * 解密字符串为数字
     */
    public static String decryptNumber(String encrypted) {
        try {
            if (encrypted == null || encrypted.isEmpty()) {
                return "";
            }

            // 不需要替换回特殊字符

            // 补全Base64编码（添加等号）
            StringBuilder sb = new StringBuilder(encrypted);
            while (sb.length() % 4 != 0) {
                sb.append('=');
            }
            encrypted = sb.toString();

            // Base64解码
            byte[] decoded = decode(encrypted);
            if (decoded.length == 0) {
                return "";
            }

            String mapped = new String(decoded, "UTF-8");

            // 反向映射表
            Map<Character, Character> reverseMapping = new HashMap<>();
            reverseMapping.put('k', '0');
            reverseMapping.put('p', '1');
            reverseMapping.put('m', '2');
            reverseMapping.put('n', '3');
            reverseMapping.put('b', '4');
            reverseMapping.put('v', '5');
            reverseMapping.put('c', '6');
            reverseMapping.put('x', '7');
            reverseMapping.put('z', '8');
            reverseMapping.put('l', '9');

            // 将字符转回数字
            StringBuilder result = new StringBuilder();
            for (char c : mapped.toCharArray()) {
                if (reverseMapping.containsKey(c)) {
                    result.append(reverseMapping.get(c));
                }
            }

            return result.toString();
        } catch (Exception e) {
            return ""; // 解析失败时返回空字符串
        }
    }

    /**
     * 验证字符串是否为加密后的格式
     */
    public static boolean isBase64Encrypted(String str) {
        if (str == null || str.trim().isEmpty() || str.length() < 4) {
            return false;
        }

        try {
            // 不需要替换回特殊字符
            String decodeStr = str;

            // 补全Base64编码
            StringBuilder sb = new StringBuilder(decodeStr);
            while (sb.length() % 4 != 0) {
                sb.append('=');
            }
            String paddedStr = sb.toString();

            // 验证是否为有效的Base64
            byte[] decoded = decode(paddedStr);
            if (decoded.length == 0) {
                return false;
            }

            String decodedStr = new String(decoded, "UTF-8");

            // 检查解码后的字符是否都在映射表中
            String validChars = "kpmnbvcxzl";
            boolean hasValidChar = false;

            for (char c : decodedStr.toCharArray()) {
                if (validChars.indexOf(c) != -1) {
                    hasValidChar = true;
                } else if (c != '\0') { // 忽略空字符
                    return false;
                }
            }

            return hasValidChar;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 测试不同长度的数字
            String[] testNumbers = {"1", "12", "123", "1234", "49", "987654321"};

            for (String number : testNumbers) {
                String encrypted = encryptNumber(number);
                String decrypted = decryptNumber(encrypted);
                System.out.println("原始数字: " + number);
                System.out.println("加密结果: " + encrypted);
                System.out.println("解密结果: " + decrypted);
                System.out.println("验证通过: " + number.equals(decrypted));
                System.out.println("--------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}